package service

import (
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/models"
	"MyBlogv2/blog-common/response"
	"github.com/gin-gonic/gin"
	"strconv"
)

func GetPermissionList(c *gin.Context) {
	permissionVoList := selectPermission("", "", 0)
	response.ResponseOK(c, permissionVoList)
	return
}
func SearchPermission(c *gin.Context) {
	permissionDesc := c.Query("permissionDesc")
	permissionKey := c.Query("permissionKey")
	permissionMenuId, _ := strconv.Atoi(c.Query("permissionMenuId"))
	permissionVoList := selectPermission(permissionDesc, permissionKey, permissionMenuId)
	response.ResponseOK(c, permissionVoList)
	return
}

func selectPermission(permissionDesc string, permissionKey string, permissionMenuId int) []models.PermissionVo {
	var permissionVoList []models.PermissionVo
	db := models.Db.Model(new(models.Permission)).
		Table("sys_permission p").
		Select("p.*,m.title as menu_name").
		Joins("left join sys_menu m on p.menu_id = m.id")
	if permissionDesc != "" {
		db.Where("p.permission_desc like ?", "%"+permissionDesc+"%")
	}
	if permissionKey != "" {
		db.Where("p.permission_key like ?", "%"+permissionKey+"%")
	}
	if permissionMenuId != 0 {
		db.Where("p.menu_id = ?", permissionMenuId)
	}
	db.Find(&permissionVoList)
	return permissionVoList

}

func GetPermissionMenuList(c *gin.Context) {
	var permissionMenuVoList []models.PermissionMenuVo
	db := models.Db.Model(new(models.PermissionMenuVo)).
		Distinct("p.menu_id").
		Table("sys_permission p").
		Select("p.menu_id,m.title as menu_name").
		Joins("left join sys_menu m on p.menu_id = m.id")
	db.Find(&permissionMenuVoList)
	response.ResponseOK(c, permissionMenuVoList)
	return

}

func AddOrUpdatePermission(c *gin.Context) {
	var permissionDto models.PermissionDto
	if err := c.ShouldBindJSON(&permissionDto); err != nil {
		response.ResponseError(c, HttpCode.PARAM_ERROR)
		return
	}
	var count int64
	models.Db.Model(new(models.Permission)).Where("permission_key = ?", permissionDto.PermissionKey).Count(&count)
	if count > 0 {
		response.CommonResponse(c, HttpCode.FAILURE, nil, "权限标识已存在")
		return
	}
	if permissionDto.Id == 0 {
		models.Db.Model(new(models.PermissionDto)).Create(&permissionDto)
	} else {
		models.Db.Model(new(models.PermissionDto)).Where("id = ?", permissionDto.Id).Updates(&permissionDto)
	}
	response.ResponseOK(c, nil)
	return

}

func GetPermission(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	var permissionDto models.PermissionDto
	models.Db.Model(new(models.PermissionDto)).Where("id = ?", id).First(&permissionDto)
	response.ResponseOK(c, permissionDto)
	return
}

func DeletePermission(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	models.Db.Model(new(models.Permission)).Where("id = ?", id).Delete(new(models.Permission))
	response.ResponseOK(c, nil)
	return
}
